package com.sneakxy.actions;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.Options;
import org.apache.commons.lang3.StringUtils;

import com.sneakxy.config.Config;
import com.sneakxy.jdbc.JdbcHelper;

public class ActionSplitTable implements Action {

	private JdbcHelper helper;
	
	private Config config;
	
	@Override
	public void execute(CommandLine command, Options options) throws Exception {
		this.config = createConfig(command, options);
		this.helper = this.config.getJdbc().createJdbcHelper();
		try {
			helper.openConnection();
			String sql = dealSql(config.getTable().getSql());
			int size = config.getTable().getSize();
			String tableOldName = config.getTable().getName();
			String charset = config.getTable().getCharset();
			String createSql = null;
			String tableName = null;
			List<String> union = new ArrayList<>();
			for(int i=0; i<size; i++) {
				tableName = StringUtils.join(tableOldName, "_", i);
				createSql = helper.getDialect().getCreateSql(tableName, sql, charset);
				union.add(tableName);
				createTable(helper, tableName, createSql);
			}
			if(size > 1) {
				createSql = helper.getDialect().getCreateUnionSql(union, tableOldName, sql, charset);
			}
			createTable(helper, tableOldName, createSql);
		} catch (ClassNotFoundException e) {
			System.out.println("驱动加载失败.");
		} catch (SQLException e) {
			System.out.println("数据库操作失败.");
			e.printStackTrace();
		} finally {
			if(helper != null) {
				helper.close();
			}
		}
	}
	
	protected void createTable(JdbcHelper helper, String table, String createSql) {
		try {
			helper.update(createSql);
			System.out.println(String.format("创建%s成功.", table));
		} catch(Exception ex) {
			System.out.println(String.format("创建%s失败.", table));
		}
	}
	
	protected String dealSql(String sql) {
		String result = StringUtils.trimToEmpty(sql);
		if(StringUtils.endsWith(result, ";")) {
			result = StringUtils.substring(result, 0, result.length() - 1);
		}
		return result;
	}

}
